<?php
namespace app\manage\controller;

use app\manage\controller\Common;
use think\console\Output;
use think\Db;
use app\manage\command\AgentPerformance;
use think\Exception;

class UseragentController extends CommonController{
    private $list = [];
    /**
     *代理商管理
     */
    public function agentList(){
        if (request()->isAjax()) {
            $param = request()->param();
            $param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 15; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
            $limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
            $param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'a.id';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

            $where = "1=1 and a.agent_type=1";
            if(isset($param['state']) && !empty($param['state'])){
                $where.= " and a.state = '".$param['state']."'";;
            }
            if(isset($param['datetimeRange']) && !empty($param['datetimeRange'])){
                $dateTime = explode(' - ', $param['datetimeRange']);
                $where.= ' and a.reg_time >= "'.strtotime($dateTime[0]).'"';
                $where.=' and a.reg_time <= "'.strtotime($dateTime[1]).'"';
            }
            if(!empty($param['account'])){
                $where.= " and a.username like '%".$param['account']."%'";
            }
            if(!empty($param['username'])){
                $where.= " and a.nickname like '%".$param['username']."%'";
            }
           
            $data = db('users')
                ->field('a.*,b.balance')
                ->alias('a')
                ->join('user_total b','a.id=b.uid','left')
                ->where($where)
                ->order($param['sortField'], $param['sortType'])
                ->limit($limitOffset, $param['limit'])
                ->paginate($param['limit'])
                ->toArray();
            return json(['code'=> 0,'msg'=> "",'data'=>$data['data'],'count'=>$data['total']]);

        }
        return view();
    }

    //代理统计计算
    protected function counts($param){
        $sysData=[];
        if(isset($param['datetime_range']) && $param['datetime_range']){
            $dateTime = explode(' - ', $param['datetime_range']);
            $start_time=strtotime($dateTime[0]);
            $end_time=strtotime($dateTime[1]);
        }else{
            $start_time=strtotime(date('Y-m-d 00:00:00'));
            $end_time=strtotime(date('Y-m-d 23:59:59'));
        }
       
        $where="1=1";
        if(isset($param['uid'])&&!empty($param['uid'])){
            $where.=" and sid=".$param['uid'];
            $uids=db('users')->where(['sid'=>$param['uid']])->column('id');
            array_push($uids, $param['uid']);
            $username=db('users')->where(['id'=>$param['uid']])->value('username');
        }else{
            $uids=[];
        }


        //今天新增会员数
        $sysData['todayUserRegNum']=db('users')->where($where." and reg_time between $start_time and $end_time")->count();

        //总数会员数 
        $sysData['totalUserRegNum']=db('users')->where($where)->count();

        //今日买入nft
        $where="1=1 and status=3 and add_time between $start_time and $end_time";
        if(isset($param['uid'])&&!empty($param['uid'])){
            $where.=" and uid in (".implode(',',$uids).")";
        }
        $sysData['todayBuyMoeny']=db('user_task')->where($where)->sum('total_price');
        
        //今日卖出nft
        $where="1=1 and status=3 and add_time between $start_time and $end_time";
        if(isset($param['uid'])&&!empty($param['uid'])){
            $where.=" and fuid in (".implode(',',$uids).")";
        }
        $sysData['todaySaleMoney']=db('user_task')->where($where)->sum('total_price');

        //今日OTC转入
        $where="1=1 and state=1 and add_time between $start_time and $end_time";
        if(isset($param['uid'])&&!empty($param['uid'])){ 
            $where.=" and uid in (".implode(',',$uids).")";
        }
        $sysData['todayRechargeMoeny']=db('user_recharge')->where($where)->sum('real_money');

        //今日OTC转出
        $where="1=1 and state=1 and set_time between $start_time and $end_time";
        if(isset($param['uid'])&&!empty($param['uid'])){ 
            $where.=" and uid in (".implode(',',$uids).")";
        }
        $sysData['todayWithMoeny']=db('user_withdrawals')->where($where)->sum('price');

       
        //总OTC转入
        $where="1=1 and state=1 ";
        if(isset($param['uid'])&&!empty($param['uid'])){ 
            $where.=" and uid in (".implode(',',$uids).")";
        }
        $sysData['totalRechargeMoeny']=db('user_recharge')->where($where)->sum('real_money');

        //总OTC转出
        $where="1=1 and state=1 ";
        if(isset($param['uid'])&&!empty($param['uid'])){ 
            $where.=" and uid in (".implode(',',$uids).")";
        }
        $sysData['totalWithMoeny']=db('user_withdrawals')->where($where)->sum('price');

        //USTD存取差
        $sysData['totalProfile']=$sysData['totalWithMoeny']-$sysData['totalRechargeMoeny'];
        return $sysData;
    }

    public function agentDetail(){
        $param = request()->param();
        if (request()->isAjax()) {
           
            $param = request()->param();
            $param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 15; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
            $limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
            $param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'a.id';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

            $where = "1=1 and a.sid={$param['uid']}";
            if(isset($param['state']) && !empty($param['state'])){
                $where.= " and a.state = '".$param['state']."'";;
            }
            if(isset($param['datetimeRange']) && !empty($param['datetimeRange'])){
                $dateTime = explode(' - ', $param['datetimeRange']);
                $where.= ' and a.reg_time >= "'.strtotime($dateTime[0]).'"';
                $where.=' and a.reg_time <= "'.strtotime($dateTime[1]).'"';
            }
            if(!empty($param['account'])){
                $where.= " and a.username like '%".$param['account']."%'";
            }
            if(!empty($param['username'])){
                $where.= " and a.nickname like '%".$param['username']."%'";
            }
           
            $data = db('users')
                ->field('a.*,b.balance')
                ->alias('a')
                ->join('user_total b','a.id=b.uid','left')
                ->where($where)
                ->order($param['sortField'], $param['sortType'])
                ->limit($limitOffset, $param['limit'])
                ->paginate($param['limit'])
                ->toArray();
            return json(['code'=> 0,'msg'=> "",'data'=>$data['data'],'count'=>$data['total']]);
        }
        
        
        $username='';
        if(isset($param['uid'])&&!empty($param['uid'])){
            $username=db('users')->where(['id'=>$param['uid']])->value('username');
        }
        

        $this->assign('username',$username);
        $this->assign('uid',isset($param['uid'])&&!empty($param['uid'])?$param['uid']:0);
        return view();
    }

    public function agentSumm(){
        $param = request()->param();
        $agentSumm = $this->counts($param);
        return json(['code'  => 0,'data'=>[$agentSumm],'count'=>1]);
    }

    /**
     * 添加代理商
     */
    public function agentAdd(){
        if (request()->isAjax()) {
            $param = request()->param();
            if(!$param){
                return false;
            }
            $nickname = $param['nickname'];
            unset($param['nickname']);
            db()->startTrans();
            //添加后台账号
            $mid = $this->agentAdminAdd($param);
            if(intval($mid)>1){
                $param['mid'] = $mid;
                //添加前台账号
                $param['nickname'] = $nickname;
                $param['agent_type'] = 1;
                $user = model("Users")->agentUserAdd($param);
                if(is_numeric($user)===true){
                    Db::commit();
                    return json(['code'  => 1]);
                }else{
                    db()->rollback();
                    return json(['code'  => 0,'msg'   => $user]);
                }
            }else{
                db()->rollback();
                return json(['code'  => 0,'msg'   => $mid]);
            }
        }else{
            return view();
        }
    }

    /*
    *添加后台代理商账号
    */
    private function agentAdminAdd($param){
        //验证数据
        $validate = new \app\manage\validate\admins;
        if (!$validate->check($param)) {
            return $validate->getError();
        }
        //添加管理员是否存在
        $is_role = model('manage')->where('username','=',$param['username'])->count();
        if($is_role){
            return '该账户已存在';
        }

        //加密
        $param['password'] = auth_code($param['password'],'ENCODE');
//        $param['safe_code'] = auth_code($param['safe_code'],'ENCODE');
        $param['safe_code'] = '000';
        $admins_id = model('manage')->insertGetId(array_filter($param));
        if ($admins_id) {//添加 代理用户数据 查看权限
            $role = model('ManageRole')->where('role_name','in',array('代理用户数据','用户详情数据','代理商管理'))->select()->toArray();
            if(!empty($role)){
                foreach ($role as $k=>$v){
                    $admins_role[$k]['uid']     		= $admins_id;
                    $admins_role[$k]['role_id'] 		= $v['id'];
                    $admins_role[$k]['sort']    		= $v['sort'];
                    $admins_role[$k]['state']    		= $v['state'];
                    $admins_role[$k]['level']  		    = $v['level'];
                    $admins_role[$k]['cid']     		= $v['cid'];
                    $admins_role[$k]['pid']     		= $v['pid'];
                    $admins_role[$k]['role_name'] 	    = $v['role_name'];
                    $admins_role[$k]['role_url'] 		= $v['role_url'];
                }
            }

            return $admins_id;
//            $auth = model('ManageUserRole')->insertAll($admins_role);
//            if($auth){
//                return $admins_id;
//            }else{
//                return '添加代理商后台权限失败';
//            }
        }else{
            return '添加代理商管理员失败';
        }
    }
    /**
     * 删除代理商
     */
    public function agentDel(){
        if (request()->isAjax()) {
            $param = request()->param();

            $id = $param['id'];
//            $ret = model('Manage')->where('id',$id)->delete();
            $ret = model('Users')->where('id',$id)->delete();
            if(!$ret) {
                return '删除失败';
            }
            return 1;
        }
    }
    /*代理商用户数据*/
    public function agentUsers(){
        if (request()->isAjax()) {
            $param = request()->param();
            $where = array();
            $page = $param['page'];
            $limit = $param['limit'];
            if(isset($param['datetime_range']) && !empty($param['datetime_range'])){
                $dateTime = explode(' - ', $param['datetime_range']);
                $where[]  ='reg_time >= "'.strtotime($dateTime[0]).'"';
                $where[]  = 'reg_time <= "'.strtotime($dateTime[1]).'"';
            }
            if(!empty($param['state'])){
                $where[] = 'a.state='.$param['state'];
            }

            if(!empty($param['username'])){
                $where[] = 'a.username like "%'.$param['username'].'%"';
            }

            if(!empty($param['account'])){
                $where[] = 'm.username like "%'.$param['account'].'%"';
            }

            $manageUserid = session('manage_userid');	//当前登录管理员
            //检查代理商信息是否在users表中，如果在就是代理商如果不在就不是代理商
            $isAgent = model('Users')->alias('a')->join('manage m',"m.id = a.mid","left")->field('m.username,a.nickname,a.id')->where('m.id',$manageUserid)->where('agent_type',1)->find();
            if (is_object($isAgent)) {
                //增加代理商条件
                $where[] = 'm.id='.$manageUserid;
            }
            if(!empty($where)){
                $where = implode(" and ",$where);
                $agentList = model('Users')->alias('a')->join('manage m',"m.id = a.mid")->field('m.username,a.nickname,a.id')->where('agent_type',1)->whereRaw($where)->page($page)->limit($limit)->select();
                $total = model('users')->alias('a')->join('manage m',"m.id = a.mid")->where('agent_type',1)->whereRaw($where)->count();
            }else{
                $agentList = model('Users')->alias('a')->join('manage m',"m.id = a.mid")->field('m.username,a.nickname,a.id')->where('agent_type',1)->page($page)->limit($limit)->select();
                $total = model('Users')->alias('a')->join('manage m',"m.id = a.mid")->where('agent_type',1)->count();
            }

            if (!empty($agentList)) {
                //	var_dump($parent);exit;
                foreach ($agentList as $key => $value) {
                    $userPerformance =model('user_performance')->field("sum(total_task_amount) as total_task_amount,sum(total_tasks) as total_tasks,sum(level_reward) as level_reward,sum(reward_value) as reward_value")->where('uid',$value['id'])->where('performance_type',2)->find();
                    $userTotal = model('user_total')->field('sum(total_recharge) as total_recharge,sum(total_withdrawals) as total_withdrawals,sum(balance) as balance')->where('uid',$value['id'])->find();
                    $value['total_task_amount'] = $userPerformance['total_task_amount'];
                    $value['total_tasks'] = $userPerformance['total_tasks'];
                    $value['reward_value'] = $userPerformance['reward_value'];
                    $value['level_reward'] = $userPerformance['level_reward'];
                    $value['total_recharge'] = $userTotal['total_recharge'];
                    $value['total_withdrawals'] = $userTotal['total_withdrawals'];
                    $value['balance'] = $userTotal['balance'];
                    $value['userTotal'] = model('Users')->where('sid',$value['id'])->count();
                    $userPersonReward=model('userPerformance')->field("sum(reward_value) as reward_value")->where('uid',$value['id'])->where('performance_type',1)->find();
                    $value['user_person_reward'] = $userPersonReward['reward_value'];
                    $agentList[$key]=$value;
                }
                return json(['code'  => 0,'data'=>$agentList,'count'=>$total]);
            }
        }
        return view();
    }

    /*代理商用户数据*/
    public function agentUsersDetail(){
        if (request()->isAjax()) {
            $param = request()->param();
            if (intval($param['id'])<=0) {
                return json(array('code'=>1,'msg'=>'上级代理商编号丢失'));
            }
            $id =  $param['id'];//上级代理商id
            $info = model('Users')->field('id,username,phone')->where('id',$id)->where('user_type',1)->find();//查出上级基本信息
            //查询用户详细数据
            if (is_object($info)) {
                $info = $info->toArray();
                $where = array();
                $page = $param['page'];
                $limit = $param['limit'];
                if(isset($param['datetime_range']) && !empty($param['datetime_range'])){
                    $dateTime = explode(' - ', $param['datetime_range']);
                    $where[]  ='reg_time >= "'.strtotime($dateTime[0]).'"';
                    $where[]  = 'reg_time <= "'.strtotime($dateTime[1]).'"';
                }
                if(!empty($param['level'])){
                    $where[] = 'vip_level='.$param['level'];
                }

                if(!empty($param['username'])){
                    $where[] = 'username like "%'.$param['username'].'%"';
                }
                if(!empty($where)){
                    $where = implode(" and ",$where);
                    $subUsers = model('Users')->field('id,vip_level,reg_time,username')->where('sid',$info['id'])->whereRaw($where)->page($page)->limit($limit )->select()->toArray();
                    $getTotal = model('Users')->field('id')->where('sid',$info['id'])->whereRaw($where)->count();
                }else{
                    $subUsers = model('Users')->field('id,vip_level,reg_time,username')->where('sid',$info['id'])->page($page)->limit($limit )->select()->toArray();
                    $getTotal = model('Users')->field('id')->where('sid',$info['id'])->count();
                }

                if(!empty($subUsers)){
                    foreach ($subUsers as $k=>$value){
                        $value['upper'] = $info['username'];
                        $userPerformance =model('user_performance')->field("sum(total_task_amount) as total_task_amount,sum(total_tasks) as total_tasks,sum(level_reward) as level_reward,sum(reward_value) as reward_value")->where('uid',$value['id'])->where('performance_type',2)->find();
                        $userTotal = model('user_total')->field('sum(total_recharge) as total_recharge,sum(total_withdrawals) as total_withdrawals,sum(balance) as balance')->where('uid',$value['id'])->find();
                        $userPersonReward=model('userPerformance')->field("sum(reward_value) as reward_value")->where('uid',$value['id'])->where('performance_type',1)->find();
                        $value['total_task_amount'] = $userPerformance['total_task_amount'];
                        $value['reg_time'] = date('Y-m-d H:i:s',$value['reg_time']);
                        $value['total_tasks'] = $userPerformance['total_tasks'];
                        $value['reward_value'] = $userPerformance['reward_value'];
                        $value['level_reward'] = $userPerformance['level_reward'];
                        $value['total_recharge'] = $userTotal['total_recharge'];
                        $value['total_withdrawals'] = $userTotal['total_withdrawals'];
                        $value['balance'] = $userTotal['balance'];
                        $value['user_person_reward'] = $userPersonReward['reward_value'];
                        $subUsers[$k] = $value;
                    }
                }
                return json(['code'  => 0,'data'=>$subUsers,'count'=>$getTotal]);
            }else{
                return json(['code'  => 1,'msg'   => "该代理商不存在"]);
            }
        }
        return view();
    }

    /**
     * 计算代理业绩
     */
    public function calculatePerformance(){
        if (request()->isAjax()) {
            $ouput = new Output();
            $count = model("UserPerformance")->calculatePerformance($ouput);
            return 1;
        }
    }

    /**
     * 计算代理佣金
     */
    public function calculateCommission(){
        if (request()->isAjax()) {
            $ouput = new Output();
            $count = model("UserPerformance")->calculateCommission($ouput);
            return 1;
        }
    }

    //佣金发放:
    public function rewardSend()
    {
        if (request()->isAjax()) {
            $param = request()->param();
            $ret = 0;
            if (isset($param["data"])&&isset($param["action"])){
                $send_state = 2;
                if ($param["action"]=="grant")
                    $send_state = 1;
                $ret = model("UserPerformance")->sendCommission($param["data"]["id"],$send_state);
            }
            return $ret;
        }
    }

    /**
     * 代理奖励设置
     */
    public function agentReward(){
        if (request()->isAjax()) {
            $param = request()->param();
            if(isset($param['reward_type'])){
                $rule = array('reward_type'=>'require','reward_config'=>"require");
                $message = array('reward_type.require'=>"个人业绩或团队业绩选项必选",
                    'reward_config.require'=>"奖励配置必填");
                $check = $this->validate($param,$rule,$message);
                if($check!=true){
                    return json(['code'  => 0,'msg'   => $check]);
                }else{
                    $param['reward_config'] = json_encode($param['reward_config']);
                    $result = model('UserAgentReward')->saveReward($param);
                    if($result==false){
                        return json(['code'  => 0,'msg'   => "保存失败"]);
                    }else{
                        return json(['code'  => 1,'msg'   => "保存成功"]);
                    }
                }
            }else{
                $UserAgentReward = model('UserAgentReward')->getList();
                return json(['code'  => 1,'msg'   => "",'data'=>$UserAgentReward]);
            }
        }else{
            return view();
        }
    }



    /**
     *代理业绩查询
     */
    public function  kpiList(){
        if (request()->isAjax()) {
            $param = request()->param();
            $where = array();
            $page = $param['page'];
            $limit = $param['limit'];
            if(isset($param['sid'])  && !empty($param['sid'])){
                $where[] = 'a.sid='.$param['sid'];
            }

            if(isset($param['datetime_range']) && !empty($param['datetime_range'])){
                $dateTime = explode(' - ', $param['datetime_range']);
                $where[]  ='cr_date >= "'.$dateTime[0].'"';
                $where[]  = 'cr_date <= "'.$dateTime[1].'"';
            }
            //用户账户
            if(!empty($param['username'])){
                $where[] = "a.uid in (select id from ly_users where username like '%".$param['username']."%')";
//                $users = model('users')->join('user_performance b','ly_users.id=b.uid','right')->field('b.uid')->where('username','LIKE', '%'.$param['username'].'%')->select();
//                if (is_object($users)) {
//                    $users = $users->toArray();
//                    $uid = array();
//                    foreach ($users as $key => $value) {
//                        $uid[] = $value['uid'];
//                    }
//                    $uid = implode(',', $uid);
//                    $where[] ='a.uid in ('.$uid.')';
//                }
            }

            //直属上级
            if(!empty($param['account'])){
                $where[] = "a.sid in (select id from ly_users where username like '%".$param['account']."%')";
//                $susers = model('users')->join('user_performance b','ly_users.id=b.sid','right')->field('b.sid')->where('username','like', '%'.$param['account'].'%')->select();
//                if (is_object($susers)) {
//                    $susers = $susers->toArray();
//                    $sid = array();
//                    foreach ($susers as $skey => $svalue) {
//                        $sid[] = $svalue['sid'];
//                    }
//                    $sid = implode(',', $sid);
//                    $where[] = 'a.sid in ('.$sid.')';
//                }
            }
            //用户等级
            if(!empty($param['level'])){
                $where[] = 'u.vip_level='.$param['level'];
            }
            //个人业绩 or 团队业绩
            $performance_type = 1;
            if(!empty($param['performance_type'])){
                $performance_type = $param['performance_type'];
            }
            $where[] = 'performance_type='.$performance_type;
            //只算天的，周和月是为了奖励使用，不算业绩
            $where[] = 'performance_period=1';
            $userPerformance = model('userPerformance')->getList($where,$page,$limit);
            $count = model('userPerformance')->getTotal($where); //总数据
            return json(['code'=> 0,'msg'=> "",'data'=>$userPerformance,'count'=>$count,'where'=>$param]);
        }
        return view();
    }



    /**
     *代理返佣奖励
     */
    public function agentCommissionReward(){
        if (request()->isAjax()) {
            $param = request()->param();
            $page = $param['page'];
            $limit = $param['limit'];
            unset($param['page']);
            unset($param['limit']);
            $where = array();
            if(isset($param['datetime_range']) && !empty($param['datetime_range'])){
                $dateTime = explode(' - ', $param['datetime_range']);
                $where[]  ='cr_date >= "'.$dateTime[0].'"';
                $where[]  = 'cr_date <= "'.$dateTime[1].'"';
            }
            //用户账户
            if(!empty($param['username'])){
                $where[] = "a.uid in (select id from ly_users where username like '%".$param['username']."%')";
//                $users = model('users')->join('user_performance b','ly_users.id=b.uid','right')->field('b.uid')->where('username','LIKE', '%'.$param['username'].'%')->select();
//                if (is_object($users)) {
//                    $users = $users->toArray();
//                    $uid = array();
//                    foreach ($users as $key => $value) {
//                        $uid[] = $value['uid'];
//                    }
//                    $uid = implode(',', $uid);
//                    $where[] ='a.uid in ('.$uid.')';
//                }
            }

            //直属上级
            if(!empty($param['account'])){
                $where[] = "a.sid in (select id from ly_users where username like '%".$param['account']."%')";
//                $susers = model('users')->join('user_performance b','ly_users.id=b.sid','right')->field('b.sid')->where('username','like', '%'.$param['account'].'%')->select();
//                if (is_object($susers)) {
//                    $susers = $susers->toArray();
//                    $sid = array();
//                    foreach ($susers as $skey => $svalue) {
//                        $sid[] = $svalue['sid'];
//                    }
//                    $sid = implode(',', $sid);
//                    $where[] = 'a.sid in ('.$sid.')';
//                }
            }
            //发放方式
            if(isset($param['sendMode'])){
                $where[] = 'send_mode='.$param['sendMode'];
            }
            //发放状态
            if (isset($param['sendState'])){
                $where[] = 'send_state='.strval($param['sendState']);
            }
            $period = array(1=>'天结',2=>"周结",3=>"月结");
            $sendState = array('未发放','已发放','已拒绝');
            $sendMode = array(1=>'自动',2=>"手动");
            if (isset($param['performance_type']) && $param['performance_type']==2) {
                //团队返佣
                $where[]='performance_type=2 and performance_period in (2,3) and reward_amount>0';
                $userPerformance = model('userPerformance')->getList($where,$page,$limit);
                $count = model('userPerformance')->getTotal($where); //总数据
                $agentReward = model('UserAgentReward')->getTeam();
                foreach ($userPerformance as $key=>$value) {
                    $value['send_mode'] = $sendMode[$value['send_mode']];
                    $value['performance_period'] = $period[$value['performance_period']]."(".$value["report_date"].")";
                    $value['send_time'] = $value['send_time']>0?date('m-d h:m:s',$value['send_time']):" ";
                    $value['send_state'] = $sendState[$value['send_state']].($value['send_state']>0?"(".$value['send_time'].")":"");
                    if($agentReward&&$agentReward['is_team_on']!=1) continue;
                    $rewardConfig = json_decode($agentReward['reward_config'],1);
                     $discount = 0;
                     try {
                         $amountLimit = 0;
                        foreach ($rewardConfig as  $v) {
                            if($v['min']<=$value['total_task_amount']  && $v['max']>=$value['total_task_amount']){
                                $discount = $v['value'];
                                $value['discount'] = $discount;  //团队返佣折扣
                                $subOrdinateTeam = model('userPerformance')->getSubOrdinateTeam($value['uid']);
                                if(is_object($subOrdinateTeam)){
                                    $subOrdinateTeam = $subOrdinateTeam->toArray();
                                    foreach ($subOrdinateTeam as $sk=>$sub){
                                        foreach ($rewardConfig as $subv){
                                            if($subv['min']<=$sub['total_task_amount']  && $subv['max']>=$sub['total_task_amount']){
                                                $amountLimit += ($discount - $subv['value'])*$sub['total_task_amount'];
                                            }
                                        }
                                        $sub['amountLimit'] = $amountLimit;
                                        $subOrdinateTeam[$sk]=$sub;
                                    }
                                }
                                $userPerformance[$key]= $value;
                            }
                        }
                     }catch (Exception $e){
                         $tt = 3;
                     }

                    $userPerformance[$key] = $value;
                }
                return json(['code'=> 0,'msg'=> "",'data'=>$userPerformance,'count'=>$count,'where'=>$param]);

            }else{
                try{
                //个人返佣
                $where[]='performance_type=1 and performance_period in (2,3) and reward_amount>0';
                $userPerformance = model('userPerformance')->getList($where,$page,$limit);
                $count = model('userPerformance')->getTotal($where); //总数据
                $agentReward = model('UserAgentReward')->getPerson();

                if (!empty($userPerformance)&&$agentReward) {
                    $discount = 0;
                    foreach ($userPerformance as $key=>$value) {
                        $value['send_mode'] = $sendMode[$value['send_mode']];
                        $value['send_time'] = $value['send_time']>0?date('m-d h:m:s',$value['send_time']):" ";
                        $value['send_state'] = $sendState[$value['send_state']].($value['send_state']>0?"(".$value['send_time'].")":"");
                        $value['performance_period'] = $period[$value['performance_period']]."(".$value["report_date"].")";;
                        $rewardConfig = json_decode($agentReward['reward_config'],1);
                        if (!empty($rewardConfig)) {
                            foreach ($rewardConfig as  $v) {
                                if($v['min']<=$value['total_task_amount']  && $v['max']>=$value['total_task_amount']){
                                    $discount = $v['value'];
                                    $value['discount'] = $discount;
                                    $userPerformance[$key]= $value;
                                }
                            }
                        }
                        $userPerformance[$key]= $value;
                    }
                }
            }catch (Exception $e){
                $tt = 3;
            }
                return json(['code'=> 0,'msg'=> "",'data'=>$userPerformance,'count'=>$count,'where'=>$param]);
            }
        }
        return view();
    }


    	/**
	 * 用户列表
	 */
	public function user(){
		if (request()->isAjax()) {
			//获取参数
			$param = input('post.');
			//查询条件组装

			//查询代理商下的会员  Elina add start ------
            $username = session('manage_username');
            $res  = model('users')->field("idcode")->where('username',$username)->find();
            $recommend =  $res['idcode'];

            $result = $this->getChilds($recommend);

            // 计算当前用户recommend
            $where[] = ['ly_users.id','in',$result];
			//查询代理商下的会员  Elina add end ------



			//用户名
			if(isset($param['username']) && $param['username']){
				$where[] = ['ly_users.username','like','%'.$param['username'].'%'];
			}
			//用户名
			if(isset($param['uid']) && $param['uid']){
				$where[] = ['ly_users.uid','=',$param['uid']];
			}
            //ip
            if(isset($param['last_ip']) && $param['last_ip']){
                $where[] = ['ly_users.last_ip','=',$param['last_ip']];
            }
			//邀请码 推荐人
			if(isset($param['idcode']) && $param['idcode']){
				$where[] = ['ly_users.recommend','=',$param['idcode']];
			}

			//余额
			if(isset($param['balance1']) && $param['balance1']){
				$where[] = ['user_total.balance','>=',$param['balance1']];
			}
			//余额
			if(isset($param['balance2']) && $param['balance2']){
				$where[] = ['user_total.balance','<=',$param['balance2']];
			}
			//用户名
			if(isset($param['state']) && $param['state']){
				$where[] = ['ly_users.state','=',$param['state']];
			}
			//用户名
			if(isset($param['is_automatic']) && $param['is_automatic']){
				$where[] = ['ly_users.is_automatic','=',$param['is_automatic']];
			}
			// 时间
			if(isset($param['datetime_range']) && $param['datetime_range']){
				$dateTime = explode(' - ', $param['datetime_range']);
				$where[]  = ['reg_time','>=',strtotime($dateTime[0])];
				$where[]  = ['reg_time','<=',strtotime($dateTime[1])];
			}

			$count              = model('Users')->join('user_total','ly_users.id = user_total.uid')->where($where)->count(); // 总记录数
			$param['limit']     = (isset($param['limit']) and $param['limit']) ? $param['limit'] : 15; // 每页记录数
			$param['page']      = (isset($param['page']) and $param['page']) ? $param['page'] : 1; // 当前页
			$limitOffset        = ($param['page'] - 1) * $param['limit']; // 偏移量
			$param['sortField'] = (isset($param['sortField']) && $param['sortField']) ? $param['sortField'] : 'reg_time';
			$param['sortType']  = (isset($param['sortType']) && $param['sortType']) ? $param['sortType'] : 'desc';

			//查询符合条件的数据
            $ipSql = " ,(select count(distinct uid) from ly_loginlog where ip=ly_users.last_ip) as ip_count";
            $totalSql = " ,(select sum(price) from ly_user_withdrawals where uid=ly_users.id and state=1) as total_amount";
			$data = model('Users')->field(['ly_users.*'.$ipSql.$totalSql,'user_total.balance','user_total.total_balance'])->join('user_total','ly_users.id = user_total.uid')->where($where)->order($param['sortField'], $param['sortType'])->limit($limitOffset, $param['limit'])->select()->toArray();

			if (count($data)==0){
			    //只查找Users:
                foreach ($where as $key=>&$value){
                    $value[0] = str_replace("ly_users.","",$value[0]);
                }
                $userData = model('Users')->where($where)->find();
                //User找到，UserTotal没找到
                if ($userData){
                    return json([
                        'code'  => 1,
                        'msg'   => '该用户存在(ID='.strval($userData["id"]).'), 但未找到该用户对应的资金账户',
                        'count' => 0,
                        'data'  => $userData
                    ]);
                }
            }
			$userState = config('custom.userState');//账号状态
			foreach ($data as $key 		=> &$value) {
                $total_amount = 0;
                if ($value['total_amount'])
                    $total_amount = $value['total_amount'];
                $value['total_amount'] = $total_amount;
				$value['reg_time'] 		= date('Y-m-d H:i:s', $value['reg_time']);
				$value['grade_name']    = config('custom.gradeName')[$value['vip_level']];
				$value['stateStr']    	= $userState[$value['state']];
				$value['isOnline'] 		= (cache('C_token_'.$value['id'])) ? '在线' : '离线';
			}
			return json([
				'code'  => 0,
				'msg'   => '',
				'count' => $count,
				'data'  => $data
			]);
		}

		return view();
	}

	    public function getChilds($idcode = 0,$type='')
    {
        if(!$type){
            $map = [
                'recommend' => $idcode,
            ];
        }else{
            $map = [
                'sid' => $idcode,
            ];
        }

        $result = model("users")->where($map)->field('id,idcode')->select()->toArray();
        if ($result) {
            foreach ($result as $val) {
                $id = (int)$val['id'];
                array_push($this->list,$val['id']);
                 $itemList = $this->getChilds($id,2);
            }

        }
        return  $this->list;
    }













}
